package HashBuck;

public class HashBuck {
    static class Node {
        public int key;
        public int value;
        public Node next;

        public Node(int key,int val) {
            this.key = key;
            this.value = val;
        }
    }

    public Node[] array;

    public int usedSize;

    public static double loadFactor=0.75;

    public HashBuck() {
        array=new Node[10];
    }

    public void put(int key,int value){
        int index=key% array.length;
        Node cur=array[index];
        // 1. 遍历当前链表,是否存在当前值
        while(cur!=null) {
            if(cur.key==key){
                cur.value=value;//更新val
                return;
            }
            cur=cur.next;
        }
        //2. 说明该值第一次出现,那么进行头插
        Node node=new Node(key,value);
        node.next=array[index];
        array[index]=node;
        usedSize++;
        //3. 检查负载因子,超过0.75就扩容
        if(getLoadFactor()>=loadFactor) {
            //扩容
            reSize();
        }
    }

    private double getLoadFactor(){
        return usedSize*1.0/array.length;
    }

    private void reSize() {
        Node[] newArray=new Node[array.length*2];
        for(int i=0;i<array.length;i++) {
            Node cur=array[i];
            while(cur!=null) {
                //遍历链表
                int newIndex=cur.key%newArray.length;//重新哈希
                Node curN=cur.next;
                cur.next=newArray[newIndex];
                newArray[newIndex]=cur;//重新头插
                //cur如何回到原链表走到下一个元素呢?在修改cur指向之前,把cur.next先存起来
                cur=curN;
            }
        }
        array=newArray;
    }

    //通过key的值找val的值
    public int get(int key) {
        int index=key% array.length;
        Node cur=array[index];
        // 1. 遍历当前链表,是否存在当前值
        while(cur!=null) {
            if(cur.key==key){
                return cur.value;
            }
            cur=cur.next;
        }
        return -1;//表示没有这个值
    }

}
